package com.ustze.ocr.type.baidu.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Maps;
import com.ustze.ocr.ocrtype.enums.OcrType;
import com.ustze.ocr.ocrtype.request.OcrRequest;
import com.ustze.ocr.type.baidu.constant.BaiduOcrApiConstant;
import com.ustze.ocr.type.baidu.utils.BaiduOcrUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

/**
 * @author zk
 * @date 2025/04/11
 */
@Service
@RequiredArgsConstructor
public class BaiduOcrService implements OcrRequest {


    private final BaiduOcrUtils baiduUtils;;

    @Override
    public Map<String, Object> ocrTable(MultipartFile file) {
        String accessToken = baiduUtils.accessToken();
        String url = String.format(BaiduOcrApiConstant.TABLE_API, accessToken);
        Map<String, Object> map = Maps.newHashMap();
        try {
            String encode = Base64.encode(file.getInputStream());
            map.put("image", encode);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        String post = HttpUtil.post(url, map);
        return BeanUtil.beanToMap(JSONObject.parseObject(post));
    }

    @Override
    public OcrType ocrType() {
        return OcrType.BAIDU;
    }
}
